package com.example.xianji.activity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.ViewPagerAdapter;

import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.X5WebView;
import com.nostra13.universalimageloader.core.ImageLoader;

import com.tencent.smtt.sdk.CookieSyncManager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

/**
 * 选型大厅详情页面--产品详情
 *
 * @author me
 */
public class Main_Choose_DaTingActivity extends Activity implements OnClickListener {
    private final long delay = 4 * 1000;
    private final int AUTO = 0;
    //    private SharedPreferences sp;
//    private Editor ed;
    private TextView product_company_name, product_title, product_tag, product_brand, product_style, product_price, product_link_name, product_telephone, product_renzheng_state;
    private X5WebView product_details;
    private RelativeLayout choose_details_back;
    private Button button_see_company, button_company_liuyan;
    private int booth_id;
    private ViewPager product_view_pager;
    private LinearLayout product_dotLayout;
    private int width;
    private int newWidth;
    private int padding;
    private ImageView[] mDots;
    private ViewPagerAdapter mViewPagerAdp;
    private ArrayList<String> image_path_list = new ArrayList<String>();
    private ImageView choose_product_iamge_collection;
    private ArrayList<ImageView> imageview_list = new ArrayList<ImageView>();
    private FrameLayout fragment_layout_product;
    private int last_index = 0;
    private PageChangeListener mPageChangeListener;
    private String[] pic;//js交互获取到的图片数组
    private Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {

            switch (msg.what) {
                case AUTO:

                    int index = product_view_pager.getCurrentItem();
                    if (product_view_pager.getCurrentItem() == image_path_list.size() - 1) {
                        index = -1;
                    }
                    product_view_pager.setCurrentItem(index + 1);
                    if (index == -1) {
                        mDots[image_path_list.size() - 1].setImageResource(R.drawable.dot_normal);
                        mDots[index + 1].setImageResource(R.drawable.dot_selected);
                    } else {
                        mDots[index + 1].setImageResource(R.drawable.dot_selected);
                        mDots[index].setImageResource(R.drawable.dot_normal);
                    }
                    mHandler.sendEmptyMessageDelayed(AUTO, delay);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__choose__da_ting);
        /****************初始化******************/
        init();
        XJApplication.cachThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                get_product_details_data();
            }
        });
    }

    private void init() {
        width = getResources().getDisplayMetrics().widthPixels;
        newWidth = (int) (divideWidth(width, 1080, 6) * 17);
        padding = (int) (divideWidth(width, 1080, 6) * 9);
        product_company_name = (TextView) findViewById(R.id.product_company_name);
        product_title = (TextView) findViewById(R.id.product_title);
        product_tag = (TextView) findViewById(R.id.product_tag);
        product_brand = (TextView) findViewById(R.id.product_brand);
        product_style = (TextView) findViewById(R.id.product_style);
        product_price = (TextView) findViewById(R.id.product_price);
        product_link_name = (TextView) findViewById(R.id.product_link_name);
        product_telephone = (TextView) findViewById(R.id.product_telephone);
        product_details = (X5WebView) findViewById(R.id.product_details);
        button_see_company = (Button) findViewById(R.id.button_see_company);
        button_company_liuyan = (Button) findViewById(R.id.button_company_liuyan);
        product_view_pager = (ViewPager) findViewById(R.id.product_view_pager);
        product_dotLayout = (LinearLayout) findViewById(R.id.product_dotLayout);
        fragment_layout_product = (FrameLayout) findViewById(R.id.fragment_layout_product);
        choose_product_iamge_collection = (ImageView) findViewById(R.id.choose_product_iamge_collection);
        product_renzheng_state = (TextView) findViewById(R.id.product_renzheng_state);
        choose_details_back = (RelativeLayout) findViewById(R.id.choose_details_back);

        mPageChangeListener = new PageChangeListener();
        choose_details_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                /************页面销毁之前移除监听事件************************/
                product_view_pager.removeOnPageChangeListener(mPageChangeListener);
                Main_Choose_DaTingActivity.this.finish();
            }
        });
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        button_see_company.setOnClickListener(this);
        button_company_liuyan.setOnClickListener(this);
        choose_product_iamge_collection.setOnClickListener(this);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        /*******************防止有黑色屏幕出现，使窗口支持透明度******************************/
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    }

    /**
     * 初始化圆点
     */
    private void initDots() {
        if (image_path_list.size() > 0) {
            mDots = new ImageView[image_path_list.size()];
            product_dotLayout.removeAllViews();
            for (int i = 0; i < image_path_list.size(); i++) {
                ImageView iv = new ImageView(this);
                LayoutParams lp = new LayoutParams(newWidth, newWidth);
                lp.leftMargin = padding;
                lp.rightMargin = padding;
                lp.topMargin = padding;
                lp.bottomMargin = padding;
                iv.setLayoutParams(lp);
                iv.setImageResource(R.drawable.dot_normal);
                product_dotLayout.addView(iv);
                mDots[i] = iv;
            }

            mDots[0].setImageResource(R.drawable.dot_selected);
        }
    }

    /**
     * 初始化viewpager图片
     */
    private void initViewPager() {
        for (int i = 0; i < image_path_list.size(); i++) {
            ImageView iv = new ImageView(this);
            /**
             * 等比例宽高
             */
            iv.setAdjustViewBounds(true);
            iv.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(image_path_list.get(i), iv);
            imageview_list.add(iv);
            final int a = i;
        }
        mViewPagerAdp = new ViewPagerAdapter(imageview_list, this);

        product_view_pager.setAdapter(mViewPagerAdp);
        product_view_pager.setCurrentItem(0);
        product_view_pager.addOnPageChangeListener(mPageChangeListener);

        mHandler.sendEmptyMessageDelayed(AUTO, delay);
    }

    public double divideWidth(int screenWidth, int picWidth, int retainValue) {
        BigDecimal screenBD = new BigDecimal(Double.toString(screenWidth));
        BigDecimal picBD = new BigDecimal(Double.toString(picWidth));
        return screenBD.divide(picBD, retainValue, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }

    public void get_product_details_data() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("product_id", getIntent().getStringExtra("product_id"));
        if (getIntent().getIntExtra("product_come_from", 0) == Contant.product_come_from_editor) {
            map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//            map.put("token", sp.getString("xianji_token", ""));
            map.put("uid", PreferenceEngine.getInstance().getInt(Constant.SP.NAME, Constant.SP.KEY_UID, 0));
//            map.put("uid", sp.getInt("uid", 0));
        }

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.product_details,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        final JSONObject OBJECT = array.getJSONObject(0);
                        Log.i("AAAAAAA", OBJECT + "");
                        booth_id = OBJECT.getInt("booth_id");
                        final JSONArray produceuploads = OBJECT.getJSONArray("produceuploads");

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    product_company_name.setText(new StringBuffer("公司名称：   ").append(OBJECT.getJSONObject("usersinfo").getString("nickname")).toString());
                                    product_title.setText(OBJECT.getString("title"));

                                    product_tag.setText(new StringBuffer(OBJECT.getString("parent_name")).append(OBJECT.getString("category_name")).append(OBJECT.getString("categorytwo_name")).
                                            append(OBJECT.getString("categorythree_name")).append(OBJECT.getString("categoryfour_name")).toString());
                                    product_brand.setText(new StringBuffer("品牌：   ").append(OBJECT.getString("brand")).toString());
                                    product_style.setText(new StringBuffer("型号：   ").append(OBJECT.getString("model")).toString());


                                    if (OBJECT.getString("price").length() == 0) {
                                        product_price.setText(new StringBuffer("价格：   ").append("面议").toString());
                                    } else {
                                        product_price.setText(new StringBuffer("价格：   ").append(OBJECT.getString("price")).append("元").toString());
                                    }
                                    product_link_name.setText(new StringBuffer("联系人：   ").append(OBJECT.getJSONObject("usersinfo").getString("name").toString()));
                                    product_telephone.setText(new StringBuffer("电话：   ").append(OBJECT.getJSONObject("usersinfo").getString("mobile")).toString());
                                    //product_details.setText(OBJECT.getString("details"));
                                    //product_details.setText(Html.fromHtml(OBJECT.getString("details"), null, null));
                                    product_details.loadDataWithBaseURL(null, OBJECT.getString("details"), "text/html", "utf-8", null);
                                    product_details.setWebViewClient(new com.example.xianji.utils.MyWebViewClient(product_details));

                                    product_details.addJavascriptInterface(new com.example.xianji.utils.Javascript(
                                                    Main_Choose_DaTingActivity.this),
                                            "myObj");
                                    if (OBJECT.getJSONObject("usersinfo").getString("authen").equals("D")) {
                                        product_renzheng_state.setText(new StringBuffer("认证状态:  ").append("未认证").toString());
                                    } else if (OBJECT.getJSONObject("usersinfo").getString("authen").equals("A")) {
                                        product_renzheng_state.setText(new StringBuffer("认证状态:  ").append("申请中").toString());
                                    } else if (OBJECT.getJSONObject("usersinfo").getString("authen").equals("N")) {
                                        product_renzheng_state.setText(new StringBuffer("认证状态:  ").append("未认证").toString());
                                    } else if (OBJECT.getJSONObject("usersinfo").getString("authen").equals("Y")) {
                                        product_renzheng_state.setText(new StringBuffer("认证状态:  ").append("认证通过").toString());
                                    }


                                    if (OBJECT.getJSONObject("usersinfo").getString("type").equals("FC") || OBJECT.getJSONObject("usersinfo").getString("type").equals("AC")) {
                                        //企业用户
                                        button_see_company.setVisibility(View.VISIBLE);
                                    } else {
                                        //个人用户
                                        button_see_company.setVisibility(View.GONE);
                                    }

                                    if (produceuploads.length() == 0) {
                                        fragment_layout_product.setVisibility(View.GONE);
                                    } else {
                                        fragment_layout_product.setVisibility(View.VISIBLE);
                                        for (int i = 0; i < produceuploads.length(); i++) {
                                            image_path_list.add(produceuploads.getJSONObject(i).getString("imageurl"));
                                        }

                                        initDots();
                                        initViewPager();
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(Main_Choose_DaTingActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_see_company) {
            Intent intent = new Intent(Main_Choose_DaTingActivity.this, Main_QiYe_DetailsActivity.class);
            intent.putExtra("gongsi_id", booth_id);
            startActivity(intent);

        } else if (v.getId() == R.id.button_company_liuyan) {
//            if (sp.getBoolean("xianji_denglu", false)) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                Intent intent = new Intent(Main_Choose_DaTingActivity.this, Main_FuWu_LiuYanActivity.class);
                intent.putExtra("liuyan_comefrom", 2);
                intent.putExtra("fuwu_id", getIntent().getStringExtra("product_id"));
                startActivity(intent);
            } else {
                Intent intent = new Intent(Main_Choose_DaTingActivity.this, Main_LoginActivity.class);
                intent.putExtra("origin_login", 53);
                startActivity(intent);
            }

        } else if (v.getId() == R.id.choose_product_iamge_collection) {
//            if (sp.getBoolean("xianji_denglu", false)) {
            if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
                XJApplication.cachThreadPool.execute(new Runnable() {

                    @Override
                    public void run() {
                        get_product_collection();
                    }
                });

            } else {
                Intent intent = new Intent(Main_Choose_DaTingActivity.this, Main_LoginActivity.class);
                intent.putExtra("origin_login", 53);
                startActivity(intent);
            }
        }
    }

    public void get_product_collection() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id", getIntent().getStringExtra("product_id"));
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        map.put("token", sp.getString("xianji_token", ""));
        map.put("type", "product");
        map.put("qiye_id", booth_id);
        map.put("title", product_title.getText().toString());

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.collection,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_Choose_DaTingActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void setCurrentDot(int currentPosition) {
        mDots[currentPosition].setImageResource(R.drawable.dot_selected);
        if (last_index != -1) {
            mDots[last_index].setImageResource(R.drawable.dot_normal);
        }
        last_index = currentPosition;
    }

    public class PageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            setCurrentDot(arg0);
        }
    }
}
